package models

import (
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	"strconv"
)

type AiCdr struct {
	Id                int64
	Account_id        int
	Callee            string
	Caller            string
	Start_time        string
	End_time          string
	Route_id          int64
	Fee_rate          float32
	Duration          int
	Bill_balance      float32
	Record_base       string
	Record_path       string
	Task_id           int64
	Call_id           string
	Intention         int
	Hangup_dispostion string
	Term_cause        string
	Term_status       string
	Talk_crycle       string
}

func (a *AiCdr) TableName() string {
	return TableName("cdr")
}

func AiCdrGetList(page, pageSize int, filters ...interface{}) ([]*AiCdr, int64) {
	offset := (page - 1) * pageSize
	list := make([]*AiCdr, 0)
	query := orm.NewOrm().QueryTable(TableName("cdr"))
	if len(filters) > 0 {
		l := len(filters)
		for k := 0; k < l; k += 2 {
			query = query.Filter(filters[k].(string), filters[k+1])
		}
	}
	total, _ := query.Count()
	_, err := query.OrderBy("-id").Limit(pageSize, offset).All(&list)
	if err != nil {
		logs.Error(err)
	}
	return list, total
}

func (a *AiCdr) Delete() error {
	if _, err := orm.NewOrm().Delete(a); err != nil {
		return err
	}
	return nil
}

//获取列表
func GetCdrInfo(userId int) (int, error) {
	var authStr = " "
	if userId != 1 {
		authStr = " and account_id=" + strconv.Itoa(userId)
	}
	sqlStr := "select count(1) " +
		"from ai_cdr " +
		"where TO_CHAR(start_time,'yyyy-MM-dd') > TO_CHAR((current_timestamp - interval '1 day'),'yyyy-MM-dd') " + authStr + ";"

	var cdrCount int
	err := orm.NewOrm().Raw(sqlStr).QueryRow(&cdrCount)
	if err != nil {
		ErrorLog(err)
		return 0, err
	}

	return cdrCount, nil
}
